package android.Spider;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class InquiriesResults extends ListActivity
{

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		m_dlgProgress = ProgressDialog.show(this, "Fetching data", "Please wait while downloading data", true, true);
		
		m_connection.Initialize(this);
		
		setListAdapter(m_listAdapter);
	}

	@Override
	protected void onDestroy()
	{
		if (m_dlgProgress != null)
			m_dlgProgress.cancel();
		
		m_connection.Unregister();
		super.onDestroy();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
    	ExpandItem();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    
	    menu.add(0, 0, "Delete", R.drawable.delete);
	    menu.add(0, 1, "Expand", R.drawable.expand);
	    return true;
	}

	@Override
	public boolean onOptionsItemSelected(Menu.Item item)
	{
    	final int nSelected = getSelectedItemPosition();
    	if (nSelected >= 0)
    	{
    	    if (item.getId() == 0)
    	    {
    	    	if (nSelected >= 0 && nSelected < m_listAdapter.getCount())
    	    	{
    		    	// We should delete this selected item from Questions and server.
    		    	Questions.Question q = m_listAdapter.GetQuestion(nSelected);
    		    	m_connection.DeleteInquiry(q.m_idQuestion);

    		    	Questions questions = Questions.Instance(this);
    		    	questions.Delete(q.m_idQuestion);

    		    	m_listAdapter.Refill();
    		    	return true;
    	    	}
    	    }
    	    else if (item.getId() == 1)
    	    {
    	    	ExpandItem();
    	    	return true;
    	    }
    	}
	    
	    return false;
	}

    XmppConnection m_connection = new XmppConnection()
    {

		@Override
		protected void OnConnected() {
			// Connection is established, try to fetch data
			RequestInquiriesResults();
		}

		@Override
		protected void OnInquiriesReceived(ArrayList<Integer> lstQuestionID, ArrayList<List<Integer>> lstOptionsCount)
		{
			if (m_dlgProgress != null)
			{
				m_dlgProgress.cancel();
				m_dlgProgress = null;
			}
			
			// Questions are now accurate. Load them.
			m_listAdapter.Refill();
		}

		@Override
		protected void OnAnswerReceived(long idQuestion, String strSender, int option)
		{
			Toast.makeText(InquiriesResults.this, "New answer received", Toast.LENGTH_SHORT).show();
			m_listAdapter.Refill();
		}
		
    };

    private abstract class InquiryListAdapter extends BaseAdapter
    {
    	abstract public void Refill();
    	abstract public Questions.Question GetQuestion(int nPos);
    }

    private InquiryListAdapter m_listAdapter = new InquiryListAdapter()
    {
		public void Refill()
		{
			Questions questions = Questions.Instance(InquiriesResults.this);
			if (SpiderListener.UserName.length() > 0)
				m_lstQuestions = questions.GetQuestions(SpiderListener.UserName);
			else
				m_lstQuestions.clear();
			
    		notifyDataSetChanged();
		}

        public int getCount() {
            return m_lstQuestions.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent)
        {
    		Questions.Question q = m_lstQuestions.get(position);
    		if (convertView == null)
    			convertView = getViewInflate().inflate(R.layout.inquiryresultsitem, null, null);
    		
			int nTotal = q.GetTotalAnswerCount();
			StringBuffer strDescription = new StringBuffer();
			for (int nOption = 0; nOption < q.m_lstOptions.size(); ++nOption)
			{
				int nOptionCount = q.GetAnswerCount(nOption);
				int nOptionPercent = nTotal != 0 ? ((nOptionCount * 100) / nTotal) : 0;
				if (nOption != 0)
					strDescription.append(", ");
				
				strDescription.append(q.m_lstOptions.get(nOption));
				strDescription.append(" - ");
				strDescription.append(nOptionPercent);
				strDescription.append("%");
				strDescription.append(" (");
				strDescription.append(nOptionCount);
				strDescription.append(")");
			}
			
        	((TextView)convertView.findViewById(R.id.QueryBodyList)).setText(strDescription);
        	((TextView)convertView.findViewById(R.id.QueryHeaderList)).setText(q.m_strMsg);
 
            return convertView;
        }

    	public Questions.Question GetQuestion(int nPos)
    	{
			return m_lstQuestions.get(nPos);
    	}

        List<Questions.Question> m_lstQuestions = new ArrayList<Questions.Question>();
    };

    private void ExpandItem()
    {
		final int nPos = getSelectedItemPosition();
		if (nPos >= 0)
		{
			Questions.Question q = m_listAdapter.GetQuestion(nPos);
			ArrayList<String> lstText = new ArrayList<String>(q.m_arrAnswers.size());
			ArrayList<Integer> lstOption = new ArrayList<Integer>(q.m_arrAnswers.size());
			
			for (int nAnswer = 0; nAnswer < q.m_arrAnswers.size(); ++nAnswer)
			{
				Questions.Question.Answer answer = q.m_arrAnswers.get(nAnswer);
				int nNewPos = 0;
				for (int i = 0; i < lstOption.size(); ++i)
				{
					if (lstOption.get(i) == answer.m_nOption)
					{
						nNewPos = i;
						break;
					}
				}
				
				lstOption.add(nNewPos, answer.m_nOption);
				lstText.add(nNewPos, "\n" + answer.m_strFrom + " (" + q.m_lstOptions.get(answer.m_nOption) + ")");
			}

			StringBuffer strVoters = new StringBuffer();
			for (int nAnswer = 0; nAnswer < lstText.size(); ++nAnswer)
				strVoters.append(lstText.get(nAnswer));
			
			new AlertDialog.Builder(InquiriesResults.this)
				.setIcon(R.drawable.popuplist)
				.setTitle("List of votes")
				.setMessage(strVoters.toString())
				.show();
		}
    }

 	ProgressDialog m_dlgProgress = null;
}
